// Copyright (C) 2020-2022 Intel Corporation
// Copyright (C) 2023-2024 CVAT.ai Corporation
//
// SPDX-License-Identifier: MIT

import React, { useEffect, useCallback } from 'react';
import { Col } from 'antd/lib/grid';
import Icon, { QuestionCircleOutlined, StopOutlined } from '@ant-design/icons';
// import Select from 'antd/lib/select';
import Button from 'antd/lib/button';
import Modal from 'antd/lib/modal';
import notification from 'antd/lib/notification';

// import { FilterIcon, FullscreenIcon, GuideIcon } from 'icons';
import config from 'config';
import { DimensionType, Job, JobStage, JobState } from 'cvat-core-wrapper';
import { Workspace } from 'reducers';

import MDEditor from '@uiw/react-md-editor';
import { Divider, Popconfirm, Tooltip } from 'antd';
import CVATTooltip from 'components/common/cvat-tooltip';
import { AnnotationStatus, JobStatusEnum } from 'typings/annotion/task';
import useAnnotation from 'hooks/useAnnotation';
import { useParams } from 'react-router-dom-v5-compat';
import useTask from './useTask';
import RejectForm from './reject-form';

interface Props {
    showStatistics(): void;
    showFilters(): void;
    changeWorkspace(workspace: Workspace): void;
    jobInstance: Job;
    workspace: Workspace;
    annotationFilters: object[];
    initialOpenGuide: boolean;
}

function RightGroup(props: Props): JSX.Element {
    const {
        // showStatistics,
        // changeWorkspace,
        // showFilters,
        // workspace,
        jobInstance,
        // annotationFilters,
        initialOpenGuide,
    } = props;

    // const filters = annotationFilters.length;
    const {
        loading,
        statusLoading,
        subTaskId,
        approval,
        imageData,
        rejectVisiable,
        rejectData,
        handleApproval,
        handleChangeImageStatus,
        handleReject,
        handleRejectSubmit,
        setRejectVisible,
        checkReview,
        handleSubmitReview,
    } = useTask();

    const actionLeft = [] as React.FC[];
    const actionRight = [] as React.FC[];
    const params = useParams();

    const jobStatus = approval.taskImageInfo.subTaskStatus as AnnotationStatus;

    const description = () => (
        <>
            <div>
                一、标注员：
                ①对图片内可识别的所有物体进行框选和标注所属废钢类别，并填写该类别下所需要录入的属性，例如厚度和杂质等。
                ②如果任务内出现不属于正常卸料时抓拍的车斗内废钢图片，可标为无效数据，但仍然需要提交初审和复审，复审通过后才认定为无需标注的无效数据。
                ③若因为标注不完整或者标注存在大量错误等原因导致初审驳回，则需要重新修改或补充完整标注后再提交初审。
            </div>
            <div>
                二、初审员：
                ①对标注员提交的所有标注项进行检查，包括图层框选是否准确，标注废钢类型和属性是否准确等，初审完成后可点击「初审通过」则进入复审流程。
                ②如果标注员已标注的图层框选或者标签有误，初审员可进行修改，但是需要由复审员最终审核判定标签是否有效。
                ③如果发现标注员标注不完整，或者标注项存在大量错误，可以对整个标注任务进行初审驳回，由标注员完善标注；驳回必须注明具体原因。
            </div>
            <div>
                三、复审员： ①审核初审员对于标注员的标注项检查是否合格。
                ②对于同一个框选图层，如果初审员进行过标签修改，则复审员必须判别标注员还是初审员的标签正确；或者认为二者标签均不正确，纠正添加复审员自己认为正确的标签。
                ③如果复审员认为初审员的审核不够完善或者存在大量错误，则可以复审驳回，由初审员再次完成初审；驳回必须注明具体原因。
            </div>
        </>
    );

    // 标注说明
    const annotationTip = () => (
        <Tooltip title={description} overlayClassName='!max-w-400px'>
            <Button type='text'>
                <QuestionCircleOutlined />
                标注说明
            </Button>
        </Tooltip>
    );
    actionLeft.push(annotationTip);

    // 状态
    const jobStatusTip = () => {
        if (jobStatus === JobStatusEnum.WAITING_ANNOTATION) {
            return (
                <Button type='text' style={{ backgroundColor: 'rgba(255, 125, 0, 0.1)' }}>
                    <div className='flex items-center gap-2 text-[#FF7D00]'>
                        <div className='w-6px h-6px bg-[#FF7D00] rounded-full' />
                        <div>待标注</div>
                    </div>
                </Button>
            );
        }
        if (jobStatus === JobStatusEnum.WAITING_FIRST_REVIEW) {
            return (
                <Button type='text' style={{ backgroundColor: 'rgba(143, 0, 255, 0.1)' }}>
                    <div className='flex items-center gap-2 text-[#8F00FF]'>
                        <div className='w-6px h-6px bg-[#8F00FF] rounded-full' />
                        <div>待初审</div>
                    </div>
                </Button>
            );
        }
        if (jobStatus === JobStatusEnum.WAITING_SECOND_REVIEW) {
            return (
                <Button type='text' style={{ backgroundColor: 'rgba(255, 0, 199, 0.1)' }}>
                    <div className='flex items-center gap-2 text-[#FF00C7]'>
                        <div className='w-6px h-6px bg-[#FF00C7] rounded-full' />
                        <div>待复审</div>
                    </div>
                </Button>
            );
        }
        if (jobStatus === JobStatusEnum.SECOND_REVIEW_APPROVED) {
            return (
                <Button type='text' style={{ backgroundColor: 'rgba(0, 180, 42, 0.1)' }}>
                    <div className='flex items-center gap-2 text-[#00B42A]'>
                        <div className='w-6px h-6px bg-[#00B42A] rounded-full' />
                        <div>复审通过</div>
                    </div>
                </Button>
            );
        }
        if (jobStatus === JobStatusEnum.FIRST_REVIEW_REJECTED) {
            return (
                <CVATTooltip overlay={approval.taskImageInfo?.auditRecord?.remark}>
                    <Button type='text' style={{ backgroundColor: 'rgba(245, 63, 63, 0.1)' }}>
                        <div className='flex items-center gap-2 text-[#F53F3F]'>
                            <div className='w-6px h-6px bg-[#F53F3F] rounded-full' />
                            <div>初审驳回</div>
                        </div>
                    </Button>
                </CVATTooltip>
            );
        }

        if (JobStatusEnum.SECOND_REVIEW_REJECTED === jobStatus) {
            return (
                <CVATTooltip overlay={approval.taskImageInfo?.auditRecord?.remark}>
                    <Button type='text' style={{ backgroundColor: 'rgba(245, 63, 63, 0.1)' }}>
                        <div className='flex items-center gap-2 text-[#F53F3F]'>
                            <div className='w-6px h-6px bg-[#F53F3F] rounded-full' />
                            <div>复审驳回</div>
                        </div>
                    </Button>
                </CVATTooltip>
            );
        }
        return (
            <Button type='text' style={{ backgroundColor: 'rgba(78, 89, 105, 0.1)' }}>
                <div className='flex items-center gap-2 text-[#4E5969]'>
                    <div className='w-6px h-6px bg-[#4E5969] rounded-full' />
                    <div>已关闭</div>
                </div>
            </Button>
        );
    };

    actionLeft.push(jobStatusTip);

    // 无效数据
    const invalidDataTip = () => (
        <Button
            type='text'
            className='!bg-[#F2F3F5]'
            loading={statusLoading}
            disabled={
                ![JobStatusEnum.WAITING_ANNOTATION, JobStatusEnum.FIRST_REVIEW_REJECTED].includes(jobStatus) ||
                params.action !== 'annotation'
            }
            onClick={handleChangeImageStatus}
        >
            <StopOutlined />
            {imageData?.temStatus === 0 ? '已标为无效数据' : '标记为无效数据'}
        </Button>
    );

    actionRight.push(invalidDataTip);

    const isApproval = params.action === 'review';

    // 提交初审
    const submitFirstReviewTip = () => (
        <Button type='primary' onClick={handleSubmitReview}>
            提交初审
        </Button>
    );
    if (
        [JobStatusEnum.WAITING_ANNOTATION, JobStatusEnum.FIRST_REVIEW_REJECTED].includes(jobStatus) &&
        params.action === 'annotation'
    ) {
        actionRight.push(submitFirstReviewTip);
    }

    // 初审驳回
    const rejectFirstReviewTip = () => (
        <Button danger onClick={() => handleReject('初审驳回', JobStatusEnum.FIRST_REVIEW_REJECTED)}>
            初审驳回
        </Button>
    );
    // 初审通过
    const approveFirstReviewTip = () => (
        <Button
            type='primary'
            loading={loading}
            onClick={() =>
                handleApproval({
                    subTaskStatus: JobStatusEnum.WAITING_SECOND_REVIEW,
                    subTaskId,
                })
            }
        >
            初审通过
        </Button>
    );

    if (
        [JobStatusEnum.WAITING_FIRST_REVIEW, JobStatusEnum.SECOND_REVIEW_REJECTED].includes(jobStatus) &&
        approval.isFirstReviewer &&
        isApproval
    ) {
        actionRight.push(rejectFirstReviewTip);
        actionRight.push(approveFirstReviewTip);
    }

    // 复审驳回
    const rejectSecondReviewTip = () => (
        <Button danger onClick={() => handleReject('复审驳回', JobStatusEnum.SECOND_REVIEW_REJECTED)}>
            复审驳回
        </Button>
    );
    // 复审通过
    const approveSecondReviewTip = () => (
        <Button type='primary' loading={loading} onClick={() => checkReview(params.jid!)}>
            复审通过
        </Button>
    );

    if (jobStatus === JobStatusEnum.WAITING_SECOND_REVIEW && approval.isSecondReviewer && isApproval) {
        actionRight.push(rejectSecondReviewTip);
        actionRight.push(approveSecondReviewTip);
    }

    const openGuide = useCallback(() => {
        const PADDING = Math.min(window.screen.availHeight, window.screen.availWidth) * 0.4;
        jobInstance
            .guide()
            .then((guide) => {
                if (guide) {
                    Modal.info({
                        icon: null,
                        width: window.screen.availWidth - PADDING,
                        className: 'cvat-annotation-view-markdown-guide-modal',
                        content: (
                            <MDEditor
                                visibleDragbar={false}
                                data-color-mode='light'
                                height={window.screen.availHeight - PADDING}
                                preview='preview'
                                hideToolbar
                                value={guide.markdown}
                            />
                        ),
                    });
                }
            })
            .catch((error: unknown) => {
                notification.error({
                    message: 'Could not receive annotation guide',
                    description: error instanceof Error ? error.message : console.error('error'),
                });
            });
    }, [jobInstance]);

    useEffect(() => {
        if (Number.isInteger(jobInstance?.guideId)) {
            if (initialOpenGuide) {
                openGuide();
            } else if (jobInstance?.stage === JobStage.ANNOTATION && jobInstance?.state === JobState.NEW) {
                let seenGuides = [];
                try {
                    seenGuides = JSON.parse(localStorage.getItem('seenGuides') || '[]');
                    if (!Array.isArray(seenGuides) || seenGuides.some((el) => !Number.isInteger(el))) {
                        throw new Error('Wrong structure stored in local storage');
                    }
                } catch (error: unknown) {
                    seenGuides = [];
                }

                if (!seenGuides.includes(jobInstance.guideId)) {
                    // open guide if the user have not seen it yet
                    openGuide();
                    const updatedSeenGuides = Array.from(
                        new Set([
                            jobInstance.guideId,
                            ...seenGuides.slice(0, config.LOCAL_STORAGE_SEEN_GUIDES_MEMORY_LIMIT - 1),
                        ]),
                    );
                    localStorage.setItem('seenGuides', JSON.stringify(updatedSeenGuides));
                }
            }
        }
    }, []);

    return (
        <Col>
            <div className='flex gap-3 items-center'>
                {actionLeft.map((Action, index) => (
                    <Action key={`left_${index}`} />
                ))}
                <Divider type='vertical' className='!mx-4 h-20px' />
                {actionRight.map((Action, index) => (
                    <Action key={`right_${index}`} />
                ))}
            </div>

            <RejectForm
                visible={rejectVisiable}
                title={rejectData.title}
                onSubmit={handleRejectSubmit}
                close={() => setRejectVisible(false)}
            />
            {/* <Button
                type='link'
                className='cvat-annotation-header-fullscreen-button cvat-annotation-header-button'
                onClick={(): void => {
                    if (window.document.fullscreenEnabled) {
                        if (window.document.fullscreenElement) {
                            window.document.exitFullscreen();
                        } else {
                            window.document.documentElement.requestFullscreen();
                        }
                    }
                }}
            >
                <Icon component={FullscreenIcon} />
                Fullscreen
            </Button> */}
            {/* { jobInstance.guideId !== null && (
                <Button
                    type='link'
                    className='cvat-annotation-header-guide-button cvat-annotation-header-button'
                    onClick={openGuide}
                >
                    <Icon component={GuideIcon} />
                    Guide
                </Button>
            )} */}
            {/* <Button
                type='link'
                className='cvat-annotation-header-info-button cvat-annotation-header-button'
                onClick={showStatistics}
            >
                <InfoCircleOutlined />
                Info
            <Button>
            <Button
                type='link'
                className={`cvat-annotation-header-filters-button cvat-annotation-header-button ${filters ?
                    'filters-armed' : ''
                }`}
                onClick={showFilters}
            >
                <Icon component={FilterIcon} />
                Filters
            </Button> */}
            {/* <div>
                <Select
                    popupClassName='cvat-workspace-selector-dropdown'
                    className='cvat-workspace-selector'
                    onChange={changeWorkspace}
                    value={workspace}
                >
                    {Object.values(Workspace).map((ws) => {
                        if (jobInstance.dimension === DimensionType.DIMENSION_3D) {
                            if (ws === Workspace.STANDARD) {
                                return null;
                            }
                            return (
                                <Select.Option disabled={ws !== Workspace.STANDARD3D} key={ws} value={ws}>
                                    {ws}
                                </Select.Option>
                            );
                        }
                        if (ws !== Workspace.STANDARD3D) {
                            return (
                                <Select.Option key={ws} value={ws}>
                                    {ws}
                                </Select.Option>
                            );
                        }
                        return null;
                    })}
                </Select>
            </div> */}
        </Col>
    );
}

export default React.memo(RightGroup);
